<template>
  <basic-container>
    <avue-crud :option="option"
               v-model:search="search"
               v-model:page="page"
               v-model="form"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange">
      <template #menu-left>
        <el-button type="danger"
                   icon="el-icon-delete"
                   plain
                   v-if="this.permission.device_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template #menu="{row,index,size}">
        <el-button text type="primary"
                   icon="el-icon-setting"
                   @click="viewDetail(row)">配置
        </el-button>
        <el-button text
                   type="primary"
                   icon="el-icon-edit"
                   @click="$refs.crud.rowEdit(row,index)">编辑
        </el-button>
        <el-button text type="primary"
                   icon="el-icon-iphone"
                   v-if="row.deviceType === 'gateway'"
                   @click="viewDevice(row)">子设备
        </el-button>
        <el-button text
                   type="primary"
                   icon="el-icon-delete"
                   @click="$refs.crud.rowDel(row,index)">删除
        </el-button>
      </template>
      <template #deviceName="{ row }">
        <el-tag size="large" style="cursor:pointer" @click="viewDetail(row)">{{ row.deviceName }}</el-tag>
      </template>
      <template #deviceName-form="{ }">
        <el-input v-model="form.deviceName" :disabled="viewMode" placeholder="请输入 deviceName， 作为设备对接参数名">
          <template #append>
            <el-button :disabled="viewMode" @click="generateDeviceName">自动生成</el-button>
          </template>
        </el-input>
      </template>
      <template #deviceNoteName-form="{ }">
        <el-input v-model="form.deviceNoteName" placeholder="请输入 备注名称， 作为设备对接的详细描述">
          <template #append>
            <el-button @click="generateDeviceNoteName">自动生成</el-button>
          </template>
        </el-input>
      </template>
      <template #uniqueNo-form="{ }">
        <el-input v-model="form.uniqueNo" placeholder="请输入 设备唯一编号， 比如mac地址，sn码等，标识设备唯一性">
          <template #append>
            <el-button @click="generateDeviceUniqueNo">自动生成</el-button>
          </template>
        </el-input>
      </template>
      <template #deviceStatus="{ row }">
        <el-tag v-if="row.deviceStatus===1" type="success" style="cursor: pointer">
          <el-icon>
            <SuccessFilled />
          </el-icon>
          {{ row.deviceStatusName }}
        </el-tag>
        <el-tag v-else-if="row.deviceStatus===2" type="danger" style="cursor: pointer">
          <el-icon>
            <WarningFilled />
          </el-icon>
          {{ row.deviceStatusName }}
        </el-tag>
        <el-tag v-else type="info" style="cursor: pointer">
          <el-icon>
            <CircleCloseFilled />
          </el-icon>
          {{ row.deviceStatusName }}
        </el-tag>
      </template>
      <template #status="{ row }">
        <el-switch
          v-model="row.status"
          inline-prompt
          @change="slotChange(row)"
          active-text="启用"
          inactive-text="禁用"
          :active-value="1"
          :inactive-value="0"
        />
      </template>
      <template #imgBox="{row}">
        <img style="width: 150px;height: 150px" :src="row.logo||defaultLogo" alt="">
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/iot/device';
import { option } from '@/option/iot/device';
import { mapGetters } from 'vuex';
import func from '@/utils/func';
import { validatenull } from '@/utils/validate';

export default {
  data() {
    return {
      productKey: '',
      form: {},
      query: {},
      search: {},
      loading: true,
      viewMode: false,
      page: {
        pageSize: 12,
        pageSizes: [12, 24, 48, 72, 96, 120],
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option(this),
      data: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.device_add, false),
        viewBtn: this.validData(this.permission.device_view, false),
        delBtn: this.validData(this.permission.device_delete, false),
        editBtn: this.validData(this.permission.device_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    defaultLogo() {
      const basePath = import.meta.env.VITE_APP_BASE;
      const logoPath = `/svg/icon1.svg`;
      return basePath === '/' ? logoPath : `${basePath}${logoPath}`;
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.productKey = this.$route.query.productKey;
      if (!validatenull(this.productKey)) {
        this.$refs.crud.option.column.filter(item => {
          if (item.prop === 'productKey') {
            item.value = this.productKey;
            item.disabled = true;
            item.search = false;
            this.onLoad(this.page, this.productKey);
          }
        });
      } else {
        this.onLoad(this.page);
      }
    },
    generateDeviceName() {
      this.form.deviceName = func.strGenerate(16);
    },
    generateDeviceNoteName() {
      this.form.deviceNoteName = func.strGenerate(22);
    },
    generateDeviceUniqueNo() {
      this.form.uniqueNo = func.strGenerate(32);
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    slotChange(row) {
      if (!row.id) {
        return;
      }
      update(row).then(
        () => {
          this.onLoad(this.page);
        },
        error => {
          window.console.log(error);
        }
      );
    },
    viewDetail(row) {
      this.$router.push({
        path: `/iot/device/detail/${row.productKey}/${row.deviceName}`
      });
    },
    viewDevice(row) {
      this.$router.push({
        path: `/iot/device/detail/${row.productKey}/${row.deviceName}`,
        query: {
          activeKey: 'subset'
        }
      });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          if (this.form.parentId <= 0) {
            this.form.parentId = null;
          }
        });
        this.viewMode = true;
      } else {
        this.viewMode = false;
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page, this.query);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page, this.query);
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      const {
        productKey,
        deviceName,
        uniqueNo,
        deviceType,
        deviceStatus,
        status,
      } = this.query;

      let values = {
        productKey_equal: !validatenull(this.productKey) ? this.productKey : productKey,
        deviceName_like: deviceName,
        uniqueNo_like: uniqueNo,
        deviceType_equal: deviceType,
        deviceStatus_equal: deviceStatus,
        status_equal: status,
      };

      getList(page.currentPage, page.pageSize, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
.imgBox {
  .avue-crud__grid__value {
    position: absolute;
    width: 150px;
    height: 150px;
    right: 20px;
    bottom: 60px;

    img {
      width: 100%;
      height: 100%;
    }
  }

  .avue-crud__grid__label {
    &:after {
      display: none;
    }
  }
}
</style>
